package com.my.handler;

import com.my.utils.AnnotationUtils;
import com.my.websocket.WebSocketHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.*;

import java.util.List;

public class WebSocketFrameHandler extends SimpleChannelInboundHandler<WebSocketFrame> {

    private WebSocketHandler webSocketHandler;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) {
        if (webSocketHandler == null) {
            List<WebSocketHandler> webSocketHandlers = AnnotationUtils.getWebSocketHandlers();
            if (!webSocketHandlers.isEmpty()) {
                webSocketHandler = webSocketHandlers.get(0);
            }
            for (int i = 0; i < webSocketHandlers.size(); i++) {
                if (i + 1 >= webSocketHandlers.size()) break;
                webSocketHandlers.get(i).addNext(webSocketHandlers.get(i + 1));
            }
        }
        if (webSocketHandler == null) {
            throw new WebSocketHandshakeException("not implemented WebSocketFrameHandler");
        }
        webSocketHandler.next(ctx, frame);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}